
import { getProperty } from '@/utils';
import { backDisaplyAdvBaseInfo, createAdvBody, getRealAdvName, setAdvName } from './adv/helper'
import Adv from './adv/adv'
import Account from './adv/account'
import Component from './adv/component'
// media Update Code
import Creativor, { Creative, CreativeGroup } from './adv/creativite'


import { getAdsTemplateList, getAdvDetail, getAdsTemplateDetail, gdtAdgroupsDetail } from '@/api/intelligent';
import Position from './adv/position';
import Market from './adv/market';
import SchedulePrice from './adv/schedulePrice';
import LoadPage from './adv/loadPage';
import Components from './adv/component/index';
import Diect from './adv/diect';
import { MAIN_JUMP_INFO } from './adv/helper';

import { useAntiFlat, useConstructor } from './adv/component/helper/useConstructor';
import MainJumpInfo from './adv/component/mainJumpInfo';
import { useTemplate } from './adv/component/helper/useTemplate';
import LibMedia from './adv/component/media/lib';
import MediaComponent from './adv/component/media/single';
function getParentName() {

}


// "ELEMENT_TYPE_VIDEO" | "ELEMENT_TYPE_IMAGE"
function makComponent(components: any) {




  components.map((component: any) => {
    const isMedia = component.element_type === 'ELEMENT_TYPE_VIDEO' || component.element_type === 'ELEMENT_TYPE_IMAGE';
    // 媒体组件
    if (isMedia) {

      const parentName = component.parent_name;

    }


  })



}

export interface IAdvState {
  modal: Adv
  accounts: Array<Account>
  creativeTemplateList: Array<any>
  accountsAuth: any;
  scroller: HTMLElement | undefined

}
const state = {
  scroller: undefined,
  // 广告模型
  modal: new Adv(),
  // 账号
  accounts: [
    // new Account({
    //   id: 23,
    //   accountCode: '36433366',
    //   accountName: '深圳市怡往实业有限公司',
    //   loginName: 'oTnUI1jFEU6s-DFJt8Yc2xti7oP4',
    //   oauthStatus: '已授权',
    //   systemStatus: '不可用',
    //   accountBalance: 0.0,
    //   accountRoleType: '广告主',
    //   accountUin: '4012484',
    //   systemIndustryName: '互联网电商服务-综合电商平台',
    //   mdmName: '深圳市怡往实业有限公司',
    //   ownerName: '斯顿'
    // })
  ],
  // 账户操作情况
  accountsAuth: {
    operation: false,
  },
  // 不同板位下的创意模版列表数据
  creativeTemplateList: []
}
const actions = {

  getRequestBody({ commit, state }: any) {
    return createAdvBody(state);
  },



  // 获取广告基础信息
  async getAdvCreativeInfo({ commit, state, dispatch }: { state: IAdvState } & any, query: any) {
    state.modal = new Adv();
    state.modal.diect.loading = true;
    state.modal.position.loading = true;
    state.modal.creativor.loading = true;
    state.modal.schedulePrice.loading = true;
    const res = await gdtAdgroupsDetail({
      adgroupId: query.adgroupId,
      accountCode: query.accountCode
    });
    const info = res.data;

    const creatives = info.creatives || {};
    state.modal.creativeInfo = info;
    state.modal.adgroupId = query.adgroupId;
    state.modal.position.siteSet = creatives.siteSetIds ? creatives.siteSetIds.split(',') : [];
    state.modal.position.siteSetType = creatives.siteSetType;
    state.modal.market.marketingTargetType = creatives.marketingTargetType;
    state.accounts = [new Account({ accountCode: creatives.accountCode })]
    const creativor = new Creativor({
    });
    await dispatch('getCreativeTemplateList');
    state.modal.creativor = creativor;
    state.modal.diect.loading = false;
    state.modal.position.loading = false;
    state.modal.creativor.loading = false;
    state.modal.schedulePrice.loading = false;
    const creativeTemplateItem = state.creativeTemplateList[0];
    if (creativeTemplateItem && creativeTemplateItem.children[0]) {
      state.modal.creativor.way = creativeTemplateItem.id;
      state.modal.creativor.creativeTemplateId = creativeTemplateItem.children[0].creativeTemplateId;
    }
    if (!state.modal.creativor.creativeTemplateId) return;
    // 构建用户
    // 获取模板信息且构建营销组件
    await dispatch('getTemplateInfo');
  },
  async getAdvDetail({ commit, state, dispatch }: any, query: any) {
    state.modal = new Adv();
    state.modal.diect.loading = true;
    state.modal.position.loading = true;
    state.modal.creativor.loading = true;
    state.modal.schedulePrice.loading = true;

    commit('CONFIG_AUTH', {
      // 账号不可操作
      account: {
        operation: false,
      }
    });
    const res = await getAdvDetail({
      adgroupId: query.adgroupId
    });
    const info = res.data;
    commit('BACK_DISPALY_ADV_BASEINFO', info);
    // 创意模块
    const creativor = new Creativor({
      creativeTemplateId: info.creativeTemplateId,
    });
    if (!info.creativeTemplateId) {
      creativor.specified_form = 0;
      creativor.deliveryMode = 'DELIVERY_MODE_COMPONENT';
    }
    // 构建用户

    await dispatch('getCreativeTemplateList');
    // 回显 【创意模式】
    state.creativeTemplateList.find((template: any) => {
      const is = template.children.find((_: any) => {
        if (!_.creativeTemplateId) {
          return _.children.find((c: any) => c.creativeTemplateId == info.creativeTemplateId);
        } else {
          return _.creativeTemplateId == info.creativeTemplateId;
        }
      });
      is && (creativor.way = template.id);
    })
    state.modal.creativor = creativor;

    // 获取模板信息且构建营销组件
    await dispatch('getTemplateInfo');
    const marketComponents = state.modal.marketComponents;
    const ectypeComponent = creativor.ectypeComponent as any;
    const unSpecifiedForm = creativor.unSpecifiedForm;
    state.modal.diect.loading = false;
    state.modal.position.loading = false;
    state.modal.creativor.loading = false;
    state.modal.schedulePrice.loading = false;



    info.accountAdgroupVoList.map((account: any, i) => {
      const { wechatChannelsId } = account;
      // account.jumpInfo = [];

      // 如果有微信渠道，就设置品牌形象为微信渠道
      if (wechatChannelsId) {
        state.modal.creativor.brandType = 'WECHAT_CHANNELS';
      }
      // 循环创意组
      const groups = account.creativeArrayList.map(({ creativeList }: any) => {
        const createGroup = new CreativeGroup();
        const creative = creativeList.map(({ creativeMediaList, creativeComponents: creativeComponentsJSON, deliveryMode, creativeName, pageType, derivedCreativeSwitch }: any) => {
          const creativeComponents = JSON.parse(creativeComponentsJSON || "{}")
          const main_jump_info = creativeComponents[MAIN_JUMP_INFO];
          const video = creativeComponents['video'] || creativeComponents['short_video'];
          // 获取当前的账号组件
          const accountComponent = state.accounts[i];

          accountComponent.wechatChannels = {
            id: wechatChannelsId,
            name: '',
            optional: []
          }
          // 落地页组件
          if (marketComponents[MAIN_JUMP_INFO] && main_jump_info) {

            main_jump_info.map((component: any, i: number) => {
              marketComponents[MAIN_JUMP_INFO]['value'].page_type = component.page_type;
              const jumpInfo = new MainJumpInfo({});
              const value = component.value || {};
              jumpInfo.back(value);
              accountComponent.jumpInfo.push(jumpInfo);
            })
          }
          // 遍历所有组件
          Object.keys(creativeComponents).map(componentType => {
            const component = (creativeComponents as any)[componentType];
            if (marketComponents[componentType]) {
              const normalValue  = marketComponents[componentType].value || {};
              marketComponents[componentType].value = component[0] ? Object.assign(normalValue, component[0].value) : normalValue;
            }
            if (componentType == 'brand') {
              // 渠道
              if (wechatChannelsId) {
                marketComponents[componentType].brand_type = 'WECHAT_CHANNELS';
              }
            }
            marketComponents[componentType] && marketComponents[componentType].reset();
          })
          const getBrandComponent = marketComponents['brand'];

          state.modal.creativor.deliveryMode = deliveryMode;
          // 设置创意名称
          const creative = new Creative({
            name: creativeName.replace(/_\d+$/, ''),
            derivedCreativeSwitch: derivedCreativeSwitch
          });
          state.modal.creativor.name = creativeName.replace(/_\d+$/, '');
          // 记录一下顺序 媒体组件 循环进入
          //
          let mediaComponentIndex = 0;
          let mediaComponentLoopCount = 0;
          const ectypeMediaComponent = ectypeComponent.media[mediaComponentIndex];

          let mediaComponent = ectypeMediaComponent ? ectypeMediaComponent.clone() : null;
          // 指定组件的循环数
          let ComponentLoopMaxCount = mediaComponent ? mediaComponent.length : 0;
          //

          (creativeMediaList || []).map((creativeMedia: any) => {
            // 文案
            if (creativeMedia.mediaType == 5 && ectypeComponent.text) {
              const textComponent = ectypeComponent.text.clone();
              textComponent.content = creativeMedia.previewUrl;
              (creative.textComponent as any).push(textComponent);
            }
            // 品牌形象跳转 数据元 creativeMedia
            if (creativeMedia.mediaType == 3 || creativeMedia.mediaType == 4) {
              state.modal.creativor.brandType = creativeMedia.mediaType;
              getBrandComponent && (getBrandComponent.value.brand_url = creativeMedia.previewUrl);

            }

            if ((creativeMedia.mediaType == 6 || creativeMedia.mediaType == 7)) {
              const media = new MediaComponent({});
              media.setSrc({
                meta_type: creativeMedia.mediaType === 6 ? 'image' : 'video',
                media_url: creativeMedia.previewUrl,
                media_id: creativeMedia.mediaId,
                cover_id: video && video[0] && video[0].value ? video[0].value.cover_id : '',
              })
              creative.libMedia.medias.push(media);
            }

            // 媒体数据
            if (creativeMedia.mediaType == 1 || creativeMedia.mediaType == 2 || creativeMedia.mediaType == 0) {
              mediaComponent.init({ ...creativeMedia });
              mediaComponent.setSrc({
                meta_type: creativeMedia.mediaType === 1 || creativeMedia.mediaType === 0 ? 'image' : 'video',
                media_url: creativeMedia.previewUrl,
                media_id: creativeMedia.mediaId,
                cover_id: video && video[0] && video[0].value ? video[0].value.cover_id : '',
                number: mediaComponentLoopCount
              });
              mediaComponentLoopCount++;
              // 如果
              if (mediaComponentLoopCount >= ComponentLoopMaxCount) {
                mediaComponentIndex++;
                (creative.mediaComponent as any).push(mediaComponent);
                if (ectypeComponent.media[0]) {
                  mediaComponentLoopCount = 0;
                  mediaComponent = ectypeComponent.media[0].clone();
                  ComponentLoopMaxCount = mediaComponent.length;
                }


              }

            }
          })
          return creative;
        });



        createGroup.creative = creative;
        return createGroup;
      });
      state.modal.creativor.groups = groups;
    })
    // state.accounts =


  },


  async getTemplateInfo({ commit, state }: any) {
    const accounts = state.accounts;
    const account = accounts[0];
    const { creativor, position, market } = state.modal;
    if (!account) return;
    commit('TRIGGER_CREATIVE_CONTENT_LOADING', true);
    // 没有模版id 且 指定创意
    // if(!creativor.creativeTemplateId && creativor.un)
    // let creativeTemplateId = creativor.creativeTemplateId;

    const res = await getAdsTemplateDetail({
      accountCode: account.accountCode,
      creativeTemplateId: creativor.creativeTemplateId,
      siteSets: position.siteSet.join(','),
      siteSetType: position.siteSetType,
      marketingTargetType: market.marketingTargetType,
      deliveryMode: creativor.deliveryMode
    });
    commit('EMPTY_CREATIVE_GROUPS');
    commit('UPDATE_MARKET_COMPONENT', res.data || { creative_components: [] });
    commit('TRIGGER_CREATIVE_CONTENT_LOADING', false);
  },







  async getCreativeTemplateList({ commit, state }: any, props: any = {}) {
    const adv = state.modal;
    const accounts = state.accounts;
    const { position, market, creativor } = adv;
    creativor.loading = true;
    const res = await getAdsTemplateList({
      siteSetIds: position.siteSet.join(','),
      siteSetType: position.siteSetType,
      marketingTargetType: market.marketingTargetType,
      accountCode: accounts[0] ? accounts[0].accountCode : undefined
    })
    state.creativeTemplateList = res.data
    const temps: any = [
      {
        name: '视频',
        creativeTemplateStyle: '视频',
        children: [],
        id: 'video'
      },
      {
        name: '图文',
        creativeTemplateStyle: '图片',
        children: [],
        id: 'image'
      }
    ]
    res.data.map((item: any) => {
      const { creativeTemplateStyle } = item;
      const temp = temps.find((item: any) => item.creativeTemplateStyle == creativeTemplateStyle);
      temp && temp.children.push(item)
    })
    state.creativeTemplateList = temps.filter((_: any) => _.children.length);
    creativor.loading = false;
    return state.creativeTemplateList
  }
}


const mutations = {
  SETTING_ADV_NAME: setAdvName,

  // 创建初始化广告
  CREATE_ADV_MODAL(state: IAdvState, props: any = {}) {
    const { retain_id } = props || {};
    const { batchId, adgroupId } = state.modal;
    state.modal = new Adv();
    state.accounts = [];
    state.creativeTemplateList = [];
    state.accountsAuth = {
      operation: true
    };
    setAdvName(state)
    // 如果保留id
    if (retain_id) {
      state.modal.adgroupId = adgroupId;
      state.modal.batchId = batchId;
    }


  },
  CONFIG_AUTH(state: IAdvState, props: any = {}) {
    const { account, adv } = props;
    if (account) {
      state.accountsAuth = account;
    }
    if (adv) {
      state.modal.auth = adv;
    }



    // state.accountsAuth =
  },
  // 更新广告信息
  UPDATE_ADV(state: IAdvState, value: any) {
    Object.keys(value).map(key => {
      (state.modal as any)[key] = value[key]
    })
  },
  SCROLL_TO_ELEMENT(state: IAdvState, element: HTMLElement) {
    if (state.scroller) {

      const { top } = element.getBoundingClientRect();

      const scrollTop = state.scroller.scrollTop;
      state.scroller.scrollTo(0, scrollTop + top - 80);
    }
  },
  SET_SCROLLER(state: IAdvState, scroller: any) {
    state.scroller = scroller;
  },
  // 在任意组件 watch(() => .value.onDefaultAction) 调用该函数来使watch生效
  /**
   * 一般用于触发组件默认watch
   * 如在xx.vue 想出发 b.vue的更新 只需要在a注册 watch(() => .value.onDefaultAction) xx.vue进行调用CONTROL_MODULE_DEFAULT_ACTION即可
   * @param state
   * @param module
   */
  CONTROL_MODULE_DEFAULT_ACTION(state: IAdvState, module: any = {}) {
    const name: any = module.name;
    (state.modal as any)[name].onDefaultAction = Date.now();
  },
  // 类似于 CONTROL_MODULE_DEFAULT_ACTION 主要用于模块数据更新的时候
  CONTROL_MODULE_INFOUPDATE_ACTION(state: IAdvState, module: any = {}) {
    const name: any = module.name;
    (state.modal as any)[name].onInfoUpdateAction = Date.now();
  },

  BACK_DISPALY_ADV_BASEINFO: backDisaplyAdvBaseInfo,

  // 触发大模块的加载状态
  TRIGGER_MODULE_LOADING(state: IAdvState, props: any) {
    const name = props.name;
    const loading = (state.modal as any)[name].loading;
    (state.modal as any)[name].loading = !loading;
  },



  // 触发创意内容的加载状态
  TRIGGER_CREATIVE_CONTENT_LOADING(state: IAdvState, flag: boolean) {
    state.modal.creativor.contentLoading = flag;
  },
  // 更新账户信息
  UPDATE_ACCOUNTS(state: IAdvState, accounts: any) {
    state.accounts = accounts;
  },
  // 更新广告模型指定的数据
  UPDATE_ADV_TARGET_VALUE(state: IAdvState, props: any) {
    const { path, value, key } = props;
    const target = getProperty(state.modal, path) as any;
    if (!target) return;
    target[key] = value;
  },
  // 设置默认的广告创意形式，
  SET_NORMAL_CREATIVE(state: IAdvState) {
    state.modal.creativor.way = state.creativeTemplateList[0].id;
  },



  // 设置默认营销组件信息
  SET_NORMAL_COMPOENT_INFO(state: IAdvState) {
    const adv = state.modal;
    const isPureVideo = adv.position.isWechatChannels || adv.market.isWxChannelsLive;
    if (isPureVideo) {
      state.modal.creativor.brandType = 'WECHAT_CHANNELS'
    } else {
      // 默认品牌形象
      state.modal.creativor.brandType = 3;
    }

  },
  // 更新版位定投的信息
  UPDATE_POSITION_SCENE_SPEC(state: IAdvState, props: any) {
    state.modal.position.scene_spec = props;
  },
  // 清空创意
  EMPTY_CREATIVE_GROUPS(state: IAdvState) {
    state.modal.creativor.groups = [];
    state.modal.marketComponents = {};
    // console.log( state.modal.creativor, ' state.modal.creativor')
  },
  EMPTY_CREATIVOR(state: IAdvState) {
    state.modal.creativor = new Creativor({});
    state.creativeTemplateList = [];
    state.modal.marketComponents = {};
  },
  EMPTY_POSITION(state: IAdvState) {
    const position = new Position({});
    state.modal.position.siteSet = position.siteSet;
    state.modal.position.scene_spec = position.scene_spec;
    state.modal.position.name = position.name;
  },

  // 更新账号渠道
  UPDATE_ACCOUNTS_CHANNEL(state: IAdvState, channels: any) {
    state.accounts.map((account, i) => {
      account.wechatChannels = Object.assign(account.wechatChannels, channels[i] || {})
    })
  },
  // 更新广告版位信息
  UPDATE_POSITION_INFO(state: IAdvState, props: any) {
    const position = state.modal.position
    Object.keys(props).map((key) => {
      (position as any)[key] = props[key]
    });

  },

  //
  UPDATE_MARKET_COMPONENT_WHILE_(state: IAdvState, props: any) {

  },

  // 更新营销组件 + 创意内容
  UPDATE_MARKET_COMPONENT(state: IAdvState, props: any) {
    state.modal.creativor.reset();
    state.modal.marketComponents = {};
    const creative_components = props.creative_components || [];
    const { marketingTargetType } = state.modal.market
    // 创建基础创意组
    const creativeGroup = new CreativeGroup();
    // 构建一个默认创意组
    creativeGroup.creative = [new Creative({})];
    const normalCreative = creativeGroup.creative[0];
    normalCreative.mediaComponent = [];
    normalCreative.textComponent = [];
    const creativor = state.modal.creativor;
    state.modal.creativor.groups = [creativeGroup];

    // const recreative_components: any = [];
    function buildTree(arr: any, parent = null) {
      const isRoot = !parent;
      let result: any = parent ? {} : [];
      const sonArr = arr.filter((v: any) => parent === null ? !v.parent_name : v.parent_name === parent);
      for (const val of sonArr) {
        const children = buildTree(arr, val.name);
        if (children) {
          val.children = children;
        }
        !isRoot ? (result[val.name] = val) : result.push(val);
      }
      return result;
    }

    state.modal.marketComponents = {};
    state.modal.creativor.ectypeComponent = {
      text: undefined,
      media: []
    };
    const unSpecifiedForm = state.modal.creativor.unSpecifiedForm;
    const afcomponents = useAntiFlat(creative_components, {
      useShowcase: state.modal.creativor.isMediaShowcase,
    });
    const MARKET_COMPONENTS: any = {};
    afcomponents.map((component: any) => {
      const tx_component = component.name == 'jump_info' ? MAIN_JUMP_INFO : component.name;
      const creativeComponent = useConstructor(Object.assign(component, {
        tx_component
      }));
      if (creativeComponent.property === 'C/T') {
        normalCreative.textComponent.push(creativeComponent);
        creativor.ectypeComponent['text'] = (creativeComponent.clone());
        return;
      }
      //
      if (creativeComponent.property === 'C/M') {

        if (unSpecifiedForm) return;
        normalCreative.mediaComponent.push(creativeComponent);
        creativor.ectypeComponent['media'].push(creativeComponent.clone());
        return;
      }
      MARKET_COMPONENTS[tx_component] = creativeComponent;
    });

    function addSpecifiedMedia() {
      if (unSpecifiedForm) {
        const libMedia = new LibMedia({});
        normalCreative.libMedia = libMedia;
        creativor.ectypeComponent['media'].push(normalCreative.libMedia.clone());
      }
    };

    addSpecifiedMedia();


    state.modal.marketComponents = Object.assign({}, MARKET_COMPONENTS);
    // 如果推广产品是视频号直播
    if (marketingTargetType === 'MARKETING_TARGET_TYPE_WECHAT_CHANNELS_LIVE') {
      const jumpComponent = state.modal.marketComponents[MAIN_JUMP_INFO];
      creativor.brandType = 'WECHAT_CHANNELS'
      jumpComponent.value.page_type = 'PAGE_TYPE_WECHAT_CHANNELS_WATCH_LIVE';
    }

  },



}

export default {
  namespaced: true,
  state,
  actions,
  mutations
}
